<template>
  <div class="container">
    <el-page-header @back="goBack" content="新建订单"></el-page-header>

    <el-form class="e-m-t-45" ref="form" :model="form" :rules="rules" label-width="160px">
      <h4>电话检索</h4>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="">
            <el-input v-model="mobile" placeholder="请填写">
              <el-button slot="append" type="button" icon="el-icon-search" :loading="loading"
                @click="checkUserData(mobile)">检索</el-button>
            </el-input>
          </el-form-item>
        </div>
      </div>
      <h4>下单信息用户</h4>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="下单电话">
            <el-input v-model="form.mobile" placeholder="下单电话" :disabled="disabled1">
              <!-- <el-button slot="append" type="button" icon="el-icon-search" :loading="loading"
                @click="checkUserData(form.mobile)">检索</el-button> -->
            </el-input>
          </el-form-item>
        </div>
        <div class="e-flex-1">
          <el-form-item label="下单用户名">
            <div class="flex align-items-center">
              <div class="e-flex-1 e-p-r-15">
                <el-input v-model="form.name" placeholder="请填写" :disabled="disabled">

                </el-input>
              </div>
              <el-radio-group v-model="form.sex" :disabled="disabled">
                <el-radio label="先生">先生</el-radio>
                <el-radio label="女士">女士</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </div>
      </div>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="上门时间" prop="doorTime">
            <el-date-picker style="width:100%" v-model="form.doorTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </div>
        <!-- <div class="e-flex-1">
          <div class="e-flex-1">
            <el-form-item label="是否为客户组" prop="regent">
              <el-switch v-model="form.regent" :disabled="disabled"></el-switch>
            </el-form-item>
          </div>
        </div> -->
        <div class="e-flex-1" v-if="form.regent">
          <el-form-item label="客户组名称" prop="enterprisename">
            <el-input v-model="form.enterprisename" placeholder="请填写" :disabled="disabled"></el-input>
          </el-form-item>
        </div>
      </div>
      <h4>上门地址信息</h4>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="姓名" prop="address.name">
            <div class="flex align-items-center">
              <div class="e-flex-1 e-p-r-15">
                <el-input v-model="form.address.name" placeholder="请填写"></el-input>
              </div>
              <el-radio-group v-model="form.address.sex">
                <el-radio :label="1">先生</el-radio>
                <el-radio :label="2">女士</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </div>
        <div class="e-flex-1">
          <el-form-item label="联系电话">
            <el-input v-model="form.address.mobile" placeholder="请填写"></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="所在地区">
            <el-cascader separator="-" @change="SelectSearchCity" filterable :props="{
              lazy: true,
              checkStrictly: true,
              lazyLoad: loadCity,
              label: 'name',
              value: 'id'
            }" placeholder="选择地区" style="width: 100%;margin-right: 20px" clearable></el-cascader>
          </el-form-item>
        </div>
      </div>
      <div class="flex">
        <div class="e-flex-1">
          <el-form-item label="地址" prop="address.address">
            <!-- <el-input v-model="form.address.address" placeholder="请输入详细地址" prefix-icon="el-icon-location-information">
              <el-button slot="append" icon="el-icon-search" @click="geoCode" :loading="loading">搜索</el-button>
            </el-input> -->
            <el-input id='tipinput' v-model="form.address.address" placeholder="请输入地址(街道、楼牌等)"
              prefix-icon="el-icon-location-information">
              <el-button slot="append" icon="el-icon-search" id="geoCode" :loading="loading">搜索</el-button>
            </el-input>
            <div id="container" class="e-m-t-10" style="width:100%;height: 300px;"></div>
            <div>地址经纬度：{{ form.address.lng }}，{{ form.address.lat }}</div>
          </el-form-item>
        </div>
      </div>
      <h4>选择品类</h4>
      <!-- 选择类型 -->
      <div class="choose-low">
        <div class="con">
          <div class="item" :class="item.choose ? 'on' : ''" v-for="(item, index) in chooseType" :key="index"
            @click="chooseTypeItem(item)">
            <div class="ico u-m-b-10">
              <el-image class="img" :src="item.icon"></el-image>
            </div>
            <div class="name"><span>{{ item.name }}</span></div>
            <div class="mark" v-if="item.choose"><span class="el-icon-check"></span></div>
            <div class="mark not" v-else></div>
          </div>
        </div>
      </div>
      <template v-if="chooseTypeArr.length > 0">
        <h4>选择重量</h4>
        <div v-for="(cell, i) in chooseTypeArr" :key="i" class="choose-weight-box">
          <div class="u-tips-color"><span class="u-font-24">{{ cell.name }}</span></div>
          <div class="choose-weight u-m-b-10">
            <div class="con">
              <div class="item" :class="item.choose ? 'on' : ''" v-for="(item, index) in cell.range" :key="index"
                @click="chooseWeightItem(cell, item)">
                <div class="mark"><span class="el-icon-check"></span>
                  <div class="c"></div>
                </div>
                <template v-if="item.id > 0">
                  <span>{{ item.min }}-{{ item.max }}KG</span>
                </template>
                <template v-else>
                  <span>拍照上传</span>
                </template>
              </div>
            </div>
          </div>
        </div>
      </template>
      <h4>上传照片</h4>
      <el-form-item>
          <div class="pics-list" v-for="(item,index) in form.pics" :key="index">
            <i class="el-icon-error" @click="delPics(index)"></i>
            <el-image 
              :src="fileURL + item" 
              class="item" 
              :preview-src-list="[fileURL + item]"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
          
          <cropper-upload :zoomScale='[1, 1]' :isCropper="false" @getUpload="handleFilesSuccess"
              class="avatar-uploader">
              <div class="avatar-uploader-icon">
                  <div><i class="el-icon-plus"></i></div>
                  <div class="e-font-14">上传照片</div>
              </div>
          </cropper-upload>
      </el-form-item>
      <el-form-item class="e-m-t-45">
        <el-button @click="goBack">返回</el-button>
        <el-button type="primary" @click="create('form')">确定新建</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
let map = {}
export default {
  layout: 'admin',
  head() {
    return {
      title: '新建订单' 
    }
  },
  data() {
    return {
      mobile:"",
      loading: false,
      form: {
        name: "",
        mobile: "",
        regent: false,
        enterprisename: "",
        sex: 1,
        // addressId: 0,
        doorTime: "",
        address: {
          name: "",
          sex: 1,
          mobile: "",
          cityId: 0,
          address: "",
          lat: 23.625349,
          lng: 113.042648
        },
        estimated: [
          // {
          //     id: 0,
          //     rangeId: 0,
          //     minAmount: 0,
          //     maxAmount: 0
          // }
        ],
        pics: []
      },
      rules: {
        name: [
          { required: true, message: '请输入下单用户名', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
        ],
        doorTime: [
          { required: true, message: '请输入上门时间', trigger: 'blur' },
        ],
        'address.name': [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        'address.mobile': [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
        ],
        'address.address': [
          { required: true, message: '请输入详情地址', trigger: 'blur' },
        ],
      },
      // 选择品类
      chooseType: [],
      chooseTypeArr: [],
      disabled: true,
      disabled1: true,

    }
  },
  mounted() {
    //获取回收品类
    this.getGoodsType().then((res) => {
      this.initMap()
    })
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    handleFilesSuccess(res, file) {
        // this.form.pics = []
        if (file.status === "success") {
            this.loading = false
            this.form.pics.push(res.path)
        }
    },
    delPics(index){
      this.form.pics.splice(index,1)
    },
    initMap() {
      let that = this

      this.$AMapLoader.load({
        key: this.AMapSetting.key,             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: this.AMapSetting.version,      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        console.log('AMap:', AMap)
        var map = new AMap.Map("container", {  //设置地图容器id
          resizeEnable: true,
          center: [this.form.address.lng, this.form.address.lat], //初始化地图中心点位置
        });

        //输入提示
        // 实例化Autocomplete
        var autoOptions = {
          // input 为绑定输入提示功能的input的DOM ID
          city: '清远',
          input: 'tipinput'
        }
        var Autocomplete = new AMap.Autocomplete(autoOptions);

        // var placeSearch = new AMap.PlaceSearch({
        //     city:'清远',
        //     map: map
        // })
        // AMap.event.addListener(Autocomplete, 'select', (e)=>{

        //     //TODO 针对选中的poi实现自己的功能
        //     placeSearch.search(e.poi.name)

        //     // e.poi.location
        //     console.log('lnglat:',e.poi.location)
        //     let lnglat = e.poi.location
        //     this.form.address.lat = lnglat.lat
        //     this.form.address.lng = lnglat.lng
        // })

        // 搜索按钮绑定事件
        var button = document.getElementById('geoCode');
        var marker = [];
        button.addEventListener("click", () => {
          var keywords = this.form.address.address;

          var autoOptions = {
            city: '0763'
          }
          var placeSearch = new AMap.PlaceSearch(autoOptions);
          placeSearch.search(keywords, function (status, result) {
            // 搜索成功时，result即是对应的匹配数据
            console.log('status:', status)
            console.log('result:', result)
            if (status == "error") {
              if (result == "USER_DAILY_QUERY_OVER_LIMIT") {
                that.$message.error('已超出了该高德地图api调用次数限制');
              }
              return
            }
            if (status == "no_data") {
                that.$message.error('搜索不到此地区');
                return
            }

            var pois = result.poiList.pois;
            // 赋值第一个结果的位置经纬度
            that.form.address.lat = pois[0].location.lat
            that.form.address.lng = pois[0].location.lng

            // 移除已创建的 marker
            map.remove(marker);
            marker = [];

            for (var i = 0; i < pois.length; i++) {
              var poi = pois[i];
              marker[i] = new AMap.Marker({
                position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                title: poi.name
              });
              marker[i].content = pois[i].address
              marker[i].location = pois[i].location
            }
            //将创建的点标记添加到已有的地图实例：
            map.add(marker);
            map.setFitView();

            var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
            marker.forEach((item) => {
              item.on('click', function (e) {
                let obj = e.target

                infoWindow.setContent(obj.content);
                infoWindow.open(map, obj.location);

                that.form.address.lat = obj.location.lat
                that.form.address.lng = obj.location.lng
                that.form.address.address = obj.content
              });
            })
          })
        })
      }).catch(e => {
        console.log(e);
      })
    },
    create(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.form)
          this.$axios.post('/Admin/User/Order/Create', this.form).then((res) => {
            this.$message.success(res.msg);
            // setTimeout(() => {
              this.$router.push({
                path: '/order/user/list'
              })
            // }, 1000)
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    SelectSearchCity(v) { //选择城市
      this.form.address.cityId = v[v.length - 1];
    },
    loadCity(node, resolve) { //加载城市
      this.$axios.post('/city/List', {
        pageIndex: 1,
        pageSize: 9999,
        pId: node.level == 0 ? '0' : node.value
      }).then((res) => {
        node = res.rows.map(function (c) {
          return {
            id: c.id,
            name: c.name,
            leaf: node.level >= 3
          }
        });
        resolve(node);
      })
    },
    geoCode() { //地理编码，根据地址获取经纬度坐标
      // var address = this.form.address.address;
      // var geocoder = new AMap.Geocoder({
      //   // city: "010", //城市设为北京，默认：“全国”
      // });
      // var marker = new AMap.Marker();
      // this.loading = true
      // geocoder.getLocation(address, (status, result) => {
      //   if (status === 'complete' && result.geocodes.length) {
      //     var lnglat = result.geocodes[0].location
      //     // document.getElementById('lnglat').value = lnglat;
      //     console.log('lnglat:', lnglat)
      //     this.form.address.lat = lnglat.lat
      //     this.form.address.lng = lnglat.lng

      //     marker.setPosition(lnglat);
      //     map.add(marker);
      //     map.setFitView(marker);
      //     this.loading = false
      //   } else {
      //     this.$message.error('根据地址查询位置失败')
      //     this.loading = false
      //   }
      // });
    },
    // 获取回收品类
    getGoodsType() {
      return this.$axios.get('/Waste/Type/List').then((res) => {
        this.chooseType = res

        this.chooseType.forEach((item) => {
          item.choose = false
          item.icon = this.fileURL + item.icon
          // item.range.unshift({
          // 	id: 0,
          // 	name: '拍照上传'
          // })
        })
      })
    },
    // 选择品类
    chooseTypeItem(item) {
      item.choose = !item.choose
      this.chooseTypeArr = this.chooseType.filter(item => item.choose)

      this.form.estimated = []
      this.chooseType.forEach((item, index) => {
        if (item.choose && item.id > 0) {
          this.form.estimated.push({
            id: item.id
          })
          item.range.forEach((cell) => { //已选中的重量赋值rangeId
            if (cell.choose) {
              this.form.estimated[index].rangeId = cell.id
            }
          })
        }
      })
      this.$forceUpdate()
    },
    // 选择重量
    chooseWeightItem(cell, item) {
      // console.log('cell:',cell)

      cell.range.map((c) => {
        // c.choose = false
        this.$set(c, 'choose', false)
      })
      this.$set(item, 'choose', true)
      // item.choose = true
      console.log('item:', item)
      // 判断是否拍照上传，只要选中了“拍照上传”按钮就显示
      this.isPhoto = false
      this.chooseType.forEach((item) => {
        item.range.forEach((cell) => {
          if (cell.choose && cell.id == 0) {
            this.isPhoto = true
          }
        })
      })

      this.form.estimated.filter(item => item.id == cell.id)[0].rangeId = item.id
      // 过滤重量选择拍照上传的品类列表
      // this.form.estimated = this.form.estimated.filter(item=>item.rangeId != 0)
      this.$forceUpdate()
    },
    // 检查手机号是否存在账户
    checkUserData(mobile) {
      this.$axios.post('/User/CheckNameMobile', {
        // id: 0,
        name: '',
        mobile: mobile
      }).then((res) => {
        console.log(res)
        this.form.enterprisename = res.enterprisename
        this.form.name = res.username
        // this.form.regent = res.regent
        // this.form.sex = res.sex
        this.form.mobile = mobile
        this.disabled1 = true
        if (this.form.name == '') {
          this.disabled = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-low {
  .con {
    display: flex;
    padding-left: 150px;

    .item {
      text-align: center;
      padding-right: 30px;
      position: relative;

      .img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
      }

      .name {
        padding-top: 10px;
      }

      .mark {
        width: 20px;
        height: 20px;
        background-color: var(--main);
        border-radius: 50%;
        position: absolute;
        right: 30px;
        bottom: 34px;
        display: flex;
        align-items: center;
        justify-content: center;

        &.not {
          background-color: #fff;
          border: 1px solid var(--main);
        }
      }

      &.on {
        .ico {
          border-color: var(--main);
        }

        color: var(--main);
      }

      .el-icon-check {
        color: #fff;
      }
    }
  }
}

.choose-weight-box {
  padding-left: 150px;
}

.choose-weight {
  display: flex;
  width: 100%;

  // overflow: auto;
  .con {
    flex: 1;
    display: flex;
    margin: 0 -5px;

    .item {
      // flex: 1;
      text-align: center;
      margin: 10px 5px;
      border: 1px solid #e4e7ed;
      line-height: 32px;
      font-size: 14px;
      border-radius: 6px;
      position: relative;
      overflow: hidden;
      width: 90px;

      .el-icon-check {
        color: #fff;
        position: relative;
        z-index: 99;
        font-size: 10px;
      }

      .mark {
        display: none;
        // border: 20rpx solid $u-color-main;
      }

      &.on {
        border-color: var(--main);

        .mark {
          display: block;
          position: absolute;
          bottom: -8px;
          right: 0;

          .icon {
            position: relative;
            z-index: 9;
          }

          .c {
            border: 8px solid #2ab6b3;
            border-top-color: transparent;
            border-left-color: transparent;
            position: absolute;
            bottom: 8px;
            right: 0;
          }
        }
      }
    }
  }
}
.avatar-uploader{
  display: inline-block;
}
.pics-list{
  display: inline-block;
  position: relative;
  .el-icon-error{
    position: absolute;
    right: 0;
    top: -7px;
    color: var(--red);
    z-index: 9;
    font-size: 22px;
    cursor: pointer;
    background: #fff;
    border-radius: 50%;
  }
  .item{
    width:150px;
    height:150px;
    border-radius: 6px;
    margin-right: 10px;
  }
}
</style>
